package org.jeecg.base.facade.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import org.jeecg.base.facade.IFacade;
import org.jeecg.common.system.query.QueryGenerator;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ：IFacadeImpl
 * @Author ：zj
 * @Date ：Created in 0:14 2020/5/20
 * @Description ：TODO
 * @Version :
 */
public abstract class IFacadeImpl<V, T, S extends IService<T>> implements IFacade<V, T> {
    @Autowired
    S service;


    @Override
    public V getById(String id) {
        return vo2Po(service.getById(id));
    }

    @Override
    public boolean removeByIds(List<String> asList) {
        return service.removeByIds(asList);
    }

    @Override
    public boolean removeById(String id) {
        return service.removeById(id);
    }

    @Override
    public boolean updateById(V vo) {
        return service.updateById(po2Vo(vo));
    }

    @Override
    public boolean save(V vo) {
        return service.save(po2Vo(vo));
    }

    @Override
    public IPage<V> page(Page<V> page, V vo, Map<String, String[]> parameterMap) {
        QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(po2Vo(vo), parameterMap);
        IPage<T> pageT = new Page<>(page.getCurrent(), page.getSize());
        pageT = service.page(pageT, queryWrapper);
        if (pageT.getRecords().size() == 0) {
            page.setRecords(Collections.emptyList());
            return page;
        }

        List<V> listVo = new ArrayList<>();

        pageT.getRecords().forEach(t ->
                {
                    listVo.add(vo2Po(t));
                }
        );
        page.setRecords(listVo);
        return page;
    }

    @Override
    public List<V> list(V vo, Map<String, String[]> parameterMap) {
        QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(po2Vo(vo), parameterMap);
        List<T> list = service.list(queryWrapper);
        if (list.size() == 0) {
            return Collections.emptyList();
        }
        List<V> listVo = new ArrayList<>();
        list.forEach(t -> {
            listVo.add(vo2Po(t));
        });
        return listVo;
    }

    @Override
    public boolean saveBatch(List<V> list) {
        List<T> listSave = new ArrayList<>(list.size());
        list.forEach(vo -> {
            listSave.add(po2Vo(vo));
        });
        return service.saveBatch(listSave);
    }
}
